<template>
  <div class="form-single-fragment" style="position: relative">
    <div class="task-title">
      <div>
        <span class="text">会议室申请</span>
        <el-tag effect="dark" size="mini" type="success"
          >当前节点：启动流程</el-tag
        >
        <!-- <el-tag  effect="dark" size="mini" type="info">{{'发起人：'}}</el-tag> -->
      </div>
    </div>
    <div class="traval_submit">
      <el-button
        slot="operator"
        type="primary"
        size="mini"
        class="submit"
        @click="onSubmitClick"
      >
        提交
      </el-button>
    </div>
    <el-form
      ref="formFlowField"
      :model="formData"
      class="full-width-input"
      :disable="readOnly"
      :rules="rules"
      style="width: 100%"
      label-width="120px"
      size="mini"
      label-position="right"
      @submit.native.prevent
    >
      <el-row :gutter="20">
        <el-col :span="24">
          <el-form-item label='会议室名称' prop="FieldFlow.roomName">
            <el-select
              class="input-item"
              v-if="!readOnly"
              v-model="formData.FieldFlow.roomName"
              :clearable="true"
              filterable
              placeholder=""
              @change="onRoomNameValueChange"
            >
              <el-option
                v-for="item in meetRoomList"
                :key="item.id"
                :value="item.id"
                :label="item.name"
              />
            </el-select>
            <span class="input-item input-label" v-else>{{
              (formData.FieldFlow.projectNameDictMap || {}).name
            }}</span>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="申请时间" prop="FieldFlow.applyDate">
            <el-date-picker
              class="input-item"
              v-if="!readOnly"
              v-model="formData.FieldFlow.applyDate"
              :clearable="true"
              format="yyyy-MM-dd HH:mm:ss"
              value-format="yyyy-MM-dd HH:mm:ss"
              type="datetime"
              align="left"
              placeholder="开始时间"
            />
            <span class="input-item input-label" v-else>{{
              formData.FieldFlow.startTime
            }}</span>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="开始时间" prop="FieldFlow.startTime">
            <el-date-picker
              class="input-item"
              v-if="!readOnly"
              v-model="formData.FieldFlow.startTime"
              :clearable="true"
              format="yyyy-MM-dd HH:mm:ss"
              value-format="yyyy-MM-dd HH:mm:ss"
              type="datetime"
              align="left"
              placeholder="开始时间"
            />
            <span class="input-item input-label" v-else>{{
              formData.FieldFlow.startTime
            }}</span>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="结束时间" prop="FieldFlow.endTime">
            <el-date-picker
              class="input-item"
              v-if="!readOnly"
              v-model="formData.FieldFlow.endTime"
              :clearable="true"
              format="yyyy-MM-dd HH:mm:ss"
              value-format="yyyy-MM-dd HH:mm:ss"
              type="datetime"
              align="left"
              placeholder="结束时间"
            />
            <span class="input-item input-label" v-else>{{
              formData.FieldFlow.endTime
            }}</span>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="申请原因" prop="FieldFlow.remark">
            <el-input
              type="textarea"
              :rows="2"
              placeholder="请输入内容"
              v-model="formData.FieldFlow.remark"
            >
            </el-input>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <label class="page-close-box">
      <el-button type="text" @click="onClose" icon="el-icon-close"></el-button>
    </label>
  </div>
</template>

<script>
import { MeetRoom } from '@/api/approve.js';
import { mapActions } from 'vuex';
/* eslint-disable-next-line */
import { findTreeNode, findTreeNodePath, findItemFromList } from '@/utils';
/* eslint-disable-next-line */
import rules from '@/utils/validate.js';
/* eslint-disable-next-line */
import { DropdownWidget } from '@/utils/widget.js';
// import flowMixins from '../../mixins/flowMixins.js';
/* eslint-disable-next-line */
import { uploadMixin, statsDateRangeMixin } from '@/core/mixins';
/* eslint-disable-next-line */
import { FieldFlowController, DictionaryController } from '@/api';
// import { FlowOperationController } from "@/api/flowController.js";
// import { globalConfig } from '@/core/config';
// import merge from 'lodash/merge';

// const processDefinitionKey = "flowField";

export default {
  name: 'formFlowField',
  props: {
    // 是否运行时任务
    isRuntimeTask: {
      type: [Boolean, String]
    },
    // 是否草稿
    isDraft: {
      type: [Boolean, String],
      default: false
    },
    // 是否只读
    readOnly: {
      type: Boolean,
      default: false
    },
    // 流程实例id
    processInstanceId: {
      type: String
    },
    // 抄送消息id
    messageId: {
      type: String
    },
    // 当前任务实例id
    taskId: {
      type: String
    },
    // 任务变量列表
    taskVariableList: {
      type: Array
    }
  },
  mixins: [uploadMixin, statsDateRangeMixin],
  data () {
    return {
      textarea: '',
      formData: {
        FieldFlow: {
          id: undefined,
          roomName: '', // 会议室名称
          applyDate: undefined, // 申请时间
          startTime: undefined, // 开始时间
          endTime: undefined, // 结束时间
          date: undefined, // 共计天数
          remark: '', // 出差事由
          // updateUserId: undefined, // 用户id
          // updateTime: undefined, // 提交时间
          createUserId: undefined, // 创建用户
          createTime: undefined // 创建时间
          // postLevel: undefined,
          // appendix: undefined,
          // isDatasourceInit: false
        }
      },
      meetRoomList: [
        { id: 1, name: '会议室' },
        { id: 2, name: '展示厅' }
      ],
      // 保存草稿后返回的taskId
      draftTaskId: undefined,
      // 保存草稿后返回的流程实例ID
      draftProcessInstanceId: undefined,
      rules: {
        'FieldFlow.roomName': [
          { required: true, message: '请输入会议室名称', trigger: 'blur' }
        ],
        'FieldFlow.applyDate': [
          { required: true, message: '请输入申请时间', trigger: 'blur' }
        ],
        'FieldFlow.startTime': [
          { required: true, message: '请输入开始时间', trigger: 'blur' }
        ],
        'FieldFlow.endTime': [
          { required: true, message: '请输入结束时间', trigger: 'blur' }
        ],
        'FieldFlow.remark': [
          { required: true, message: '请输入申请原因', trigger: 'blur' }
        ]
      },
      formFlowField: {
        formFilter: {},
        formFilterCopy: {},
        clockIn: {
          impl: new DropdownWidget(this.loadClockInDropdownList)
        },
        isInit: false
      }
    }
  },
  methods: {
    // 关闭当前页面
    onClose () {
      this.$router.go(-1)
    },
    // 会议室下拉选改变
    onRoomNameValueChange (value) {
      this.formData.FieldFlow.roomName = this.meetRoomList.find((item) => item.id === value).name
    },
    // 提交会议申请
    onSubmitClick (val, options) {
      MeetRoom.add(this, {
        flowTaskCommentDto: {approvalType: 'agree'},
        meetroomDto: {
          roomName: this.formData.FieldFlow.roomName,
          applyDate: this.formData.FieldFlow.applyDate,
          startTime: this.formData.FieldFlow.startTime,
          endTime: this.formData.FieldFlow.endTime,
          remark: this.formData.FieldFlow.remark
        },
        taskVariableData: {...this.getUserInfo}
      }).then(res => {
        this.$message.success('提交成功')
        this.$router.go(-1)
      })
    },
    // 流程操作
    handlerOperation (operation, copyItemList) {
      return new Promise((resolve, reject) => {
        this.$refs.formFlowField.validate((valid) => {
          if (!valid) return reject();
          this.preHandlerOperation(operation, this.isDraft)
            .then((res) => {
              // 加签、减签操作
              if (
                operation.type === this.SysFlowTaskOperationType.CO_SIGN ||
                operation.type === this.SysFlowTaskOperationType.SIGN_REDUCTION
              ) {
                return this.submitConsign(
                  (res || {}).assignee,
                  operation.type === this.SysFlowTaskOperationType.CO_SIGN
                );
              }
              // 驳回操作
              if (
                operation.type === this.SysFlowTaskOperationType.REJECT ||
                operation.type === this.SysFlowTaskOperationType.REJECT_TO_TASK
              ) {
                // return FlowOperationController.rejectRuntimeTask(this, {
                //   processInstanceId: this.processInstanceId,
                //   taskId: this.taskId,
                //   targetTaskKey: (res || {}).targetTaskKey,
                //   taskComment: (res || {}).message,
                //   taskVariableData: {
                //     latestApprovalStatus: operation.latestApprovalStatus,
                //   },
                // });
              }
              // 驳回到起点
              if (
                operation.type === this.SysFlowTaskOperationType.REJECT_TO_START
              ) {
                // return FlowOperationController.rejectToStartUserTask(this, {
                //   processInstanceId: this.processInstanceId,
                //   taskId: this.taskId,
                //   taskComment: (res || {}).message,
                //   taskVariableData: {
                //     latestApprovalStatus: operation.latestApprovalStatus,
                //   },
                // });
              }
              // 撤销操作
              if (operation.type === this.SysFlowTaskOperationType.REVOKE) {
                this.$confirm('是否撤销此任务？')
                  .then((res) => {
                    // return FlowOperationController.rejectHistoricTask(this, {
                    //   processInstanceId: this.processInstanceId,
                    //   taskId: this.taskId,
                    //   taskComment: '任务处理人撤销任务',
                    //   taskVariableData: {
                    //     latestApprovalStatus: operation.latestApprovalStatus
                    //   }
                    // });
                  })
                  .catch((e) => {
                    return Promise.reject(e);
                  });
              }
              let formData = this.getMasterData(
                operation.type,
                (res || {}).assignee
              );
              let params = {
                taskId: this.taskId || this.draftTaskId,
                processInstanceId:
                  this.processInstanceId || this.draftProcessInstanceId,
                flowTaskCommentDto: {
                  taskComment: (res || {}).message,
                  approvalType: operation.type,
                  delegateAssginee:
                    operation.type === this.SysFlowTaskOperationType.TRANSFER
                      ? (res || {}).assignee
                      : undefined
                },
                taskVariableData: {
                  ...formData.taskVariableData,
                  latestApprovalStatus: operation.latestApprovalStatus
                },
                copyData: (copyItemList || []).reduce((retObj, item) => {
                  retObj[item.type] = item.id;
                  return retObj;
                }, {})
              };
              // 非只读状态下，提交修改数据
              if (!this.readOnly) {
                // 主表数据
                params.fieldFlowDto = {
                  ...formData.masterData
                };
                // 关联数据
                params = {
                  ...params,
                  ...formData.relationData
                };
              }

              return FieldFlowController.submitUserTaskFlowField(this, params);
            })
            .then((res) => {
              this.reloadMessage(this);
              if (
                operation.type !== this.SysFlowTaskOperationType.CO_SIGN &&
                operation.type !== this.SysFlowTaskOperationType.SIGN_REDUCTION
              ) {
                this.$message.success(operation.label + '成功！');
              }
              resolve();
            })
            .catch((e) => {
              console.log(e);
            });
        });
      });
    },
    // 保存草稿
    handlerDraft () {
      return new Promise((resolve, reject) => {
        let formData = this.getFormDataImpl();
        let params = {
          // processDefinitionKey: processDefinitionKey,
          processInstanceId:
            this.processInstanceId || this.draftProcessInstanceId,
          fieldFlowDto: {
            ...formData.masterData
          },
          ...formData.relationData
        };
        FieldFlowController.startAndSaveDraftFlowField(this, params)
          .then((res) => {
            this.$message.success('草稿保存成功！');
            this.draftProcessInstanceId = res.data.processInstanceId;
            this.draftTaskId = res.data.taskId;
            resolve();
          })
          .catch((e) => {
            reject(e);
          });
      });
    },
    // 获取表单数据
    getFormDataImpl () {
      // 一对一、一对多、多对多关联数据
      let relationData = {};

      return {
        masterData: {
          ...this.formData.FieldFlow
        },
        relationData: relationData
      };
    },
    // 获取流程表单数据
    getMasterData (operationType, assignee) {
      let taskVariableData;
      if (
        Array.isArray(this.taskVariableList) &&
        this.taskVariableList.length > 0
      ) {
        taskVariableData = this.taskVariableList.reduce((retObj, item) => {
          retObj[item.variableName] =
            this.formData.FieldFlow[item.variableName];
          return retObj;
        }, {});
      }
      // 会签操作设置多实例处理人集合
      assignee = assignee && assignee !== '' ? assignee.split(',') : undefined;
      if (operationType === this.SysFlowTaskOperationType.MULTI_SIGN) {
        if (taskVariableData == null) taskVariableData = {};
        taskVariableData.assigneeList = assignee;
      } else if (operationType === this.SysFlowTaskOperationType.SET_ASSIGNEE) {
        if (taskVariableData == null) taskVariableData = {};
        taskVariableData.appointedAssignee = Array.isArray(assignee)
          ? assignee[0]
          : undefined;
      }

      return {
        ...this.getFormDataImpl(),
        taskVariableData
      };
    },
    // 初始化流程表单
    initFormData () {
      if (!this.isStartFlow) {
        // 流程办理
        let params = {
          processInstanceId: this.processInstanceId,
          taskId: this.taskId
        };
        let httpCall = null;
        if (this.isDraft || this.isDraft === 'true') {
          // 草稿数据
          // httpCall = FlowOperationController.viewDraftData(this, {
          //   processDefinitionKey: processDefinitionKey,
          //   processInstanceId: this.processInstanceId,
          // });
        } else if (this.messageId != null) {
          // 抄送消息
          // httpCall = FlowOperationController.viewCopyBusinessData(this, {
          //   messageId: this.messageId,
          // });
        } else {
          httpCall =
            this.taskId && this.isRuntime
              ? FieldFlowController.viewTaskBusinessDataFlowField(this, params)
              : FieldFlowController.viewHistoricTaskBusinessDataFlowField(
                this,
                params
              );
        }
        httpCall
          .then((res) => {
            this.formData.FieldFlow = { ...res.data };
            this.formFlowField.clockIn.impl.onVisibleChange(true);
            this.formFlowField.projectName.impl.onVisibleChange(true);
            // 获取一对多、多对多数据
            this.refreshFormFlowField(true);
          })
          .catch((e) => {});
      } else {
        // 启动流程
      }
    },
    onCancel (isSuccess) {
      if (this.observer != null) {
        this.observer.cancel(isSuccess);
      }
    },
    /**
     * 抵消打卡下拉数据获取函数
     */
    loadClockInDropdownList () {
      return new Promise((resolve, reject) => {
        let params = {};
        DictionaryController.dictClockIn(this, params)
          .then((res) => {
            resolve(res.getList());
          })
          .catch((e) => {
            reject(e);
          });
      });
    },
    /**
     * 抵消打卡选中值改变
     */
    onClockInValueChange (value) {},
    /**
     * 项目名称下拉数据获取函数
     */
    loadProjectNameDropdownList () {
      return new Promise((resolve, reject) => {
        let params = {};
        DictionaryController.dictProject(this, params)
          .then((res) => {
            resolve(res.getList());
          })
          .catch((e) => {
            reject(e);
          });
      });
    },

    /**
     * 更新外勤申请
     */
    refreshFormFlowField (reloadData = false) {
      if (!this.formFlowField.isInit) {
        // 初始化下拉数据
      }
      this.formFlowField.isInit = true;
    },
    formInit () {
      this.initFormData();
    },
    ...mapActions(['reloadMessage'])
  },
  computed: {
    isStartFlow () {
      return this.processInstanceId == null;
    },
    isRuntime () {
      return typeof this.isRuntimeTask === 'string'
        ? this.isRuntimeTask === 'true'
        : this.isRuntimeTask;
    }
  },
  mounted () {
    // 初始化页面数据
    this.formInit();
  }
};
</script>
<style scoped>
.task-title {
  display: flex;
  justify-content: space-between;
  padding-bottom: 5px;
  margin-bottom: 10px;
  border-bottom: 3px solid #409eff;
}
.task-title .text {
  height: 28px;
  line-height: 28px;
  font-weight: 600;
  font-size: 16px;
  color: #383838;
}
.task-title .el-tag {
  margin-left: 10px;
}
.traval_submit{
  text-align: right;
}
.submit {
  padding: 9px 15px;
  font-size: 12px;
  border-radius: 3px;
  margin-bottom: 10px;
}

</style>
